package chances.epg.config;

import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.ServletContext;

import chances.epg.commons.utils.PathUtils;

/**
 * @author Coffee
 *
 */
public class EpgSiteContext {

	private String siteCode;
	
	private String contextPath;

	private Map<String, Object> attrs = new ConcurrentHashMap<String, Object>();

	public void setContextPath(String contextPath) {
		this.contextPath = contextPath;
	}

	public final static String defaultBizName = "default.bizCode";

	public static EpgSiteContext get(ServletContext servletContext, String code) {
		return (EpgSiteContext) servletContext.getAttribute("site_" + code);
	}

	public static void save(ServletContext servletContext, EpgSiteContext context) {
		context.contextPath = servletContext.getContextPath();
		servletContext.setAttribute("site_" + context.getSiteCode(), context);
	}
	public String getSiteRoot(){
		return PathUtils.join(this.contextPath,this.siteCode);
	}
	public String getHome(){
		return PathUtils.join(this.contextPath,this.siteCode,this.getDefaultBizCode());
	}
	public String getString(String name) {
		Object value = attrs.get(name);
		if (value == null) {
			return "";
		} else {
			return value.toString();
		}
	}

	public String getDefaultBizCode() {
		return this.getString(defaultBizName);
	}

	public EpgSiteContext(String site) {
		super();
		this.siteCode = site;

	}

	public EpgSiteContext(String name, Map<String, Object> params) {
		this(name);
		attrs.putAll(params);
	}

	public Object getAttribute(String name) {
		return attrs.get(name);
	}

	public void removeAttribute(String name) {
		attrs.remove(name);
	}

	public void setAttribute(String name, Object value) {
		attrs.put(name, value);
	}

	public Iterator<String> getNames() {
		return attrs.keySet().iterator();
	}

	public String getSiteCode() {
		return siteCode;
	}

	public void setSiteCode(String siteCode) {
		this.siteCode = siteCode;
	}

	public String getContextPath() {
		return this.contextPath;
	}

}
